
import http from 'axios'
import {baseUrl} from './baseUrl'
import {toast} from '../utils/toast'
import {stringutils} from '../utils/stringutils'
import store from '../store'
import router from '../router'
//导入axios
var base_url = baseUrl.getBaseUrl();
console.log(`当前环境是：${process.env.NODE_ENV} ${base_url}`);
var axios = http.create({
    baseUrl: base_url,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', //Form Data格式
        'X-REQUESTED-WITH': 'xmlhttprequest',
        'Request-App': 'web',
        'lang': 'zh_CN',
        'ApiToken':store.getters.token,
    },
});
export const ajax = function (action,data,async,isSplice,type,successfn) {
    var url = action;
    async = (async ==null || async =="" || typeof (async) == "undefined") ? true : async;
    type = (type == null || type == "" || typeof (type) == "undefined") ? "POST" : type;
    data = (data == null || data == "" || typeof (data) == "undefined") ? {"date": new Date().getTime()} : data;
    //是否要把传的值拼在接口里
    if(isSplice){
        for (let i in data) {
            url += '/'+data[i]
        }
    }else{
        //使用get,delete方法的时候将参数拼入url中
        if (type == 'GET'||type=='DELETE') {
            for (let i in data) {
                if (url.indexOf("?") != -1) {
                    url += '&' + i + '=' + data[i]
                } else {
                    url += '?' + i + '=' + data[i]
                }
            }
        }
    }
    // 发送 ajax 请求
    axios({
            method: (type == null || type == "" || typeof (type) == "undefined") ? "POST" : type, // default,
            url: base_url + url,
            data: data,
            timeout: 20000,
        }).then(function (info) {
			var res = info.data;
			//登录失效
			if (res.code == '20401') {
                toast.warning("请重新登录!");
                stringutils.clearData();
                setTimeout(() => {
                    router.push('/index');
                }, 1000);
                return false;
			}
            successfn(res);
        })
        .catch(function (e) {
            window.console.log(e);
            toast.error("网络错误~");
        });
};
//请求超时
// function timeOut() {
//     Toast("Time out");
// }